package com.skytech.component.monitor.enterprise_data_monitoring;


import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.util.ChromeBrowser;
import com.skytech.component.monitor.util.ElementAbstractUrl;
import com.skytech.component.monitor.util.SaveDataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class HeNanService implements CrawlerScript {


    @Autowired
    private SaveDataUtil saveDataUtil;

    @Autowired
    private ChromeBrowser chromeBrowser;
    private static final Logger log = LoggerFactory.getLogger(HeNanService.class);
    private static final String province = "河南";

    public void start() {

        ChromeDriver driver = chromeBrowser.getChromeDriver();

        try {
            driver.get("http://www.hnep.gov.cn:98/");//打开网页
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

            partClickNext(driver);
        } catch (Exception e) {
            log.error("{}--网页打开失败--{}", driver.getCurrentUrl(), e.getMessage());
        } finally {
            driver.quit();

            log.info("数据爬取结束");
        }


    }

    private void partClickNext(ChromeDriver driver) {
        String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
        Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
        Elements allElements = parse.getAllElements();
        List<String> urlList = ElementAbstractUrl.links(allElements.select("#UpdatePanel3 > div.qx_list > ul li a"));

        goDetail(driver, urlList);

    }

    private void goDetail(ChromeDriver driver, List<String> urlList) {
        for (String url : urlList) {
            try {
                driver.get(url);
            } catch (Exception e) {
                log.error("{}--网页打开失败--{}", driver.getCurrentUrl(), e.getMessage());
                continue;
            }

            try {
                WebElement webElement = driver.findElementByXPath("//*[@id='form1']/div[3]/div[3]/div[2]/div[1]/div[3]/ul/li[2]/a");
                webElement.click();
            } catch (Exception e) {
                log.error("元素点击失败--{}", e.getMessage());
                continue;
            }
            List<MonitorData> monitorDataList = new ArrayList<>();
            try {
                bodyClickNext(driver, monitorDataList, null);
            } catch (Exception e) {
                log.error(e.getMessage());
                continue;
            }

            saveDataUtil.saveTag(monitorDataList, province);



        }
    }

    private void bodyClickNext(ChromeDriver driver, List<MonitorData> monitorDataList, String html) {
        String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
        if (html != null) {
            if (html.equals(htmlNew)) {
                log.error("两次链接内容相同,当前页--{}", driver.getCurrentUrl());
                return;
            }
        }
        html = htmlNew;

        Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
        Elements allElements = parse.getAllElements();
        String name = allElements.select("#enpNameSpan").text();

        Elements elements = allElements.select("#tbdata_auto > tbody tr:nth-child(n+3)");
        if (!elements.isEmpty()) {
            // if (!elements.get(0).text().contains("无数据")) {

            for (Element element : elements) {
                String rowspan = element.getElementsByTag("td").select("#rpdata_auto_td_autodata_0").attr("rowspan");
                //  String state=element.getElementsByTag("td").select("#rpdata_auto_td_autodata_0").text();
                MonitorData monitorData = new MonitorData();
                if (!rowspan.isEmpty()) {
                    monitorData.setProvince(province);
                    monitorData.setId(UUID.randomUUID().toString());
                    monitorData.setCompanyName(name);
                    monitorData.setMonitorTime(element.getElementsByTag("td").get(1).text());
                    monitorData.setMonitorInfo(element.getElementsByTag("td").get(2).text());
                    monitorData.setMonitorPoint(element.getElementsByTag("td").get(3).text());
                    monitorData.setMonitorValue(element.getElementsByTag("td").get(4).text());
                    monitorData.setMonitorStandardValue(element.getElementsByTag("td").get(7).text());
                    monitorData.setOverproof(element.getElementsByTag("td").get(8).text());
                    monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    if (!monitorDataList.contains(monitorData)) {
                        monitorDataList.add(monitorData);
                    } else {
                        return;
                    }
                } else {
                    monitorData.setProvince(province);
                    monitorData.setId(UUID.randomUUID().toString());
                    monitorData.setCompanyName(name);
                    monitorData.setMonitorTime(element.getElementsByTag("td").get(1).text());
                    monitorData.setMonitorInfo(element.getElementsByTag("td").get(2).text());
                    monitorData.setMonitorPoint(element.getElementsByTag("td").get(3).text());
                    monitorData.setMonitorValue(element.getElementsByTag("td").get(4).text());
                    monitorData.setMonitorStandardValue(element.getElementsByTag("td").get(6).text());
                    monitorData.setOverproof(element.getElementsByTag("td").get(7).text());
                    monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    if (!monitorDataList.contains(monitorData)) {
                        monitorDataList.add(monitorData);
                    } else {
                        return;
                    }
                }
            }
            log.info("当前页--{}", driver.getCurrentUrl());
            try {
                WebElement webElement = driver.findElementByXPath("//*[@id='Asp_AutoData']/table/tbody/tr/td[1]/a[3]");
                webElement.click();
                Thread.sleep(1000);
                bodyClickNext(driver, monitorDataList, html);
            } catch (Exception e) {
                log.error("点击下一页出错--{}", e.getMessage());
                return;
            }

        }

    }


}
